<template>
  <!-- 客户列表 -->
  <view>
    <view class="top-fixed">
      <view class="top-search clearfix">
        <u-icon name="search" size="32" color="#999"></u-icon>
        <input
          class="top-input"
          confirm-type="search"
          placeholder-class="input-pl"
          placeholder="订单编号、收货人、商品名称、备注"
          type="text"
          v-model="search_form.keyword"
          @confirm="getData"
        />
        <u-icon
          v-show="search_form.keyword"
          @click="clearKeyword('keyword')"
          class="icon-close"
          name="close"
          size="32"
          color="#999"
        ></u-icon>
      </view>
      <view class="search-sel">
        <view class="search-sel-li" @click="openTime('start')">
          <text class="sel-label sel-name" v-if="startTime">{{
            startTime
          }}</text>
          <text class="sel-label" v-else>起始日期</text>
          <i
            v-if="startTime"
            class="ibonfont ibonic_searchclosed"
            @click.stop="clearKeyword('startTime')"
          ></i>
          <u-icon
            v-else
            class="ic-down"
            name="arrow-down"
            size="16"
            color="#fb5904"
          ></u-icon>
        </view>
        <view class="search-sel-li" @click="openTime('end')">
          <text class="sel-label sel-name" v-if="endTime">{{ endTime }}</text>
          <text class="sel-label" v-else>结束日期</text>
          <i
            v-if="endTime"
            class="ibonfont ibonic_searchclosed"
            @click.stop="clearKeyword('endTime')"
          ></i>
          <u-icon
            v-else
            class="ic-down"
            name="arrow-down"
            size="16"
            color="#fb5904"
          ></u-icon>
        </view>
        <!-- <view class="search-sel-li">
          <view class="search-sel-li" @click="showRight = true">
            <text class="sel-label">筛选</text>
            <i class="ibonfont ibonshaixuan"></i>
            <image class="ic-down" src="../../static/img/ic-down.png" mode="aspectFit"></image>
          </view>
        </view> -->
      </view>
    </view>
    <view class="container-view">
      <scroll-view
        :lower-threshold="42"
        @scrolltolower="scrollLoading"
        scroll-y
        class="list-ul"
      >
        <uniSwipeAction
          v-for="(item, index) in order_list"
          :option="swipe_options"
          :key="index"
          @click="confirmOrder($event, item)"
        >
          <view class="list-item clearfix" @click="goDetail(item)">
            <view
              class="float_left sel-view"
              @click="item.checked = !item.checked"
              v-if="source === 2"
            >
              <i class="ibonfont ibonxuanze" v-if="!item.checked"></i>
              <i class="ibonfont ibonxuanze_xuanzhong" v-else></i>
            </view>
            <view class="float_left">
              <view class="list-label clearfix">
                <view class="float_left list-name">{{
                  item.customerName
                }}</view>
                <view class="float_right status-text">
                  <uniTag :inverted="true" size="small" type="warning">{{
                    item.orderMsg
                  }}</uniTag>
                </view>
              </view>
              <view class="list-cont clearfix">
                <view class="float_left">
                  <i class="ibonfont ibonbianhao"></i>
                  {{ item.no }}
                </view>
                <view
                  class="float_right mobile"
                  @click.stop="phoneCall(item.receiveData.mobile)"
                >
                  <i class="ibonfont ibondianhua"></i>
                  {{ item.receiveData.mobile }}
                </view>
              </view>
              <view class="list-cont clearfix">
                <view class="float_left">
                  <i class="ibonfont ibonshijian"></i>
                  {{ $utils.formatDate(item.createTime) }}
                </view>
                <view class="float_right error-color"
                  >¥{{ item.payAmount }}</view
                >
              </view>
              <view class="list-cont clearfix">
                <view
                  class="float_left success-color"
                  style="font-weight: 600"
                  >{{ item.verifyCode }}</view
                >
                <view class="float_right">{{ item.shopName }}</view>
              </view>
              <view class="list-cont clearfix"
                >备注：{{ item.remark || "无备注" }}</view
              >
              <view class="list-cont clearfix" style="text-align: right"
                ><view @click.stop="toPrint(item)" class="uniTag-moni"
                  >小票打印</view
                ></view
              >
            </view>
            <view class="float_right more-right"
              ><i class="ibonfont ibonjinru"></i
            ></view>
          </view>
        </uniSwipeAction>
        <uni-load-more
          v-show="loading_status !== 'more'"
          :status="loading_status"
        ></uni-load-more>
        <view style="height: 120rpx" v-if="source === 2"></view>
      </scroll-view>
    </view>
    <uni-drawer
      class="drawer-view"
      :visible="showRight"
      mode="right"
      @close="showRight = false"
    >
      <view class="search-ul">
        <view class="search-item">
          <view class="search-label">客户</view>
          <view class="search-value">
            <view
              class="search-input clearfix"
              @click="goPage('/pages/Customer/CustomerList?source=1')"
            >
              <text class="float_left" v-if="customerName">{{
                customerName
              }}</text>
              <text class="input-pl float_left" v-else>请选择</text>
              <i class="ibonfont ibonjinru float_right"></i>
              <i
                class="ibonfont ibonic_searchclosed float_right"
                v-show="customerName"
                @click.stop="clearSearch('customerName')"
              ></i>
            </view>
          </view>
        </view>
        <view class="search-item">
          <view class="search-label">客户类型</view>
          <view class="search-value">
            <StatusSel
              @pickerChange="pickerCustomerTypeChange"
              :options="customerType"
            >
              <view class="search-input clearfix">
                <text class="float_left" v-if="customerTypeName">{{
                  customerTypeName
                }}</text>
                <text class="input-pl float_left" v-else>请选择</text>
                <i class="ibonfont ibonjinru float_right"></i>
                <i
                  class="ibonfont ibonic_searchclosed float_right"
                  v-show="customerTypeName"
                  @click.stop="clearSearch('customerTypeName')"
                ></i>
              </view>
            </StatusSel>
          </view>
        </view>
        <view class="search-item">
          <view class="search-label">业务员</view>
          <view class="search-value">
            <view
              class="search-input clearfix"
              @click="goPage('/pagesA/systemSet/StaffList?source=1')"
            >
              <text class="float_left" v-if="staffName">{{ staffName }}</text>
              <text class="input-pl float_left" v-else>请选择</text>
              <i class="ibonfont ibonjinru float_right"></i>
              <i
                class="ibonfont ibonic_searchclosed float_right"
                v-show="staffName"
                @click.stop="clearSearch('staffName')"
              ></i>
            </view>
          </view>
        </view>
      </view>
      <view class="search-bo-btn">
        <view class="sb-btn-li" @click="resetSearch">重置</view>
        <view class="sb-btn-li" @click="searchList">确认</view>
      </view>
    </uni-drawer>
    <uni-calendar
      ref="unitime"
      :date="detalutTime"
      :insert="false"
      @cancel="timeClose"
      @confirm="timeConfirm"
    />
    <!-- 新增订单按钮 -->
    <view
      class="add-btn-fixed"
      @click="goAddOrder"
      v-if="$accessCheck($Access.addSaleOrder)"
    >
      <text class="add-btn-icon">+</text>
    </view>
  </view>
</template>

<script>
import uniSwipeAction from "@/components/common/uni-swipe-action/uni-swipe-action.vue";
import uniLoadMore from "@/components/common/uni-load-more/uni-load-more.vue";
import uniTag from "@/components/common/uni-tag/uni-tag.vue";
import StatusSel from "@/components/StatusSel.vue";
import uniDrawer from "@/components/common/uni-drawer/uni-drawer.vue";
import uniCalendar from "@/components/common/uni-calendar/uni-calendar.vue";

export default {
  components: {
    uniSwipeAction,
    uniLoadMore,
    uniTag,
    StatusSel,
    uniDrawer,
    uniCalendar,
  },
  data() {
    return {
      route_type: "",
      customerType: [],
      staffName: "",
      timeType: "",
      customerTypeName: "",
      customerName: "",
      detalutTime: "",
      showRight: false,
      startTime: "",
      endTime: "",
      source: "",
      order_list: [],
      pageSize: 10,
      page: 1,
      pageTotal: 0,
      keyword: "",
      loading_status: "noMore",
      regionName: "",
      search_form: {
        keyword: "",
        provinceCode: "",
        cityCode: "",
        districtCode: "",
        start: "",
        end: "",
        customerId: "",
        customerType: "",
        salesManId: "",
      },
      customerSel: "",
      staffSel: "",
      swipe_options: [],
      loadingMore: false, // 新增：防止并发加载
    };
  },
  onNavigationBarButtonTap() {
    if (!this.$accessCheck(this.$Access.addSaleOrder)) {
      this.$u.toast("抱歉，您没有新建权限");
      return;
    }
    this.goPage("/pagesB/order/SaleOrderAdd");
  },
  onLoad(options) {
    this.getAllOrder();
    this.getAllCustomerSource();
  },
  onPullDownRefresh() {
    this.getAllOrder();
  },
  onShow() {
    if (this.CustomerSel) {
      this.search_form.customerId = this.CustomerSel.id;
      this.customerName = this.CustomerSel.name;
    }
    if (this.staffSel) {
      this.search_form.salesManId = this.staffSel.id;
      this.staffName = this.staffSel.staffName;
    }
  },
  onReachBottom() {
    // 新增：监听页面触底，触发加载
    this.scrollLoading();
  },
  methods: {
    // 单据小票打印
    async toPrint(row) {
      uni.showLoading();
      //   try {
      //     const response = await this.$http.post("/api/orders/print", {
      //       objectId: row.id,
      //       objectType: 23,
      //     });
      //     this.$u.toast("操作成功");
      //   } catch (error) {
      //     console.error("打印失败:", error);
      //     this.$u.toast("打印失败");
      //   }
      uni.hideLoading();
    },
    openTime(type) {
      this.timeType = type;
      this.$refs.unitime.open();
    },
    timeClose() {
      if (this.timeType === "start") {
        this.startTime = "";
        this.search_form.start = "";
      } else {
        this.endTime = "";
        this.search_form.end = "";
      }
      this.searchList();
    },
    // 时间
    timeConfirm(e) {
      const dateToStamp = this.$utils.dateToStamp(e.fulldate + " 00:00:00");
      if (this.timeType === "start") {
        this.startTime = e.fulldate;
        this.search_form.start = dateToStamp;
      } else {
        this.endTime = e.fulldate;
        this.search_form.end = dateToStamp + 86399;
      }
      this.searchList();
    },
    // 客户类型
    pickerCustomerTypeChange(row) {
      this.search_form.customerType = row.value;
      this.customerTypeName = row.value ? row.label : "";
    },
    goDetail(row) {
      if (!this.$accessCheck(this.$Access.saleOrderListGetOrderInfoById)) {
        return;
      }
      this.goPage(
        `/pages/order/OrderDetail?id=${row.id}&userCenterId=${row.userCenterId}&type=${this.route_type}`
      );
    },
    searchList() {
      this.showRight = false;
      this.page = 1;
      this.getData();
    },
    // 获取列表
    async getAllOrder() {
      this.loading_status = "loading";
      try {
        const response = await this.$u.api.getAllOrder({
          page: this.page,
          pageSize: this.pageSize,
          search: {
            orderType: 23,
          },
        });
        const data = response.data;
        const cData = data.data || [];
        if (this.page === 1) {
          this.order_list = cData;
        } else {
          this.order_list = this.order_list.concat(cData);
        }
        this.pageTotal = data.pageTotal || 0;
      } catch (error) {
        console.error("获取订单列表失败:", error);
        this.$u.toast("获取订单列表失败");
      }
      this.loading_status = "more";
      uni.stopPullDownRefresh();
    },
    // 订单搜索searchOrder
    async searchOrder() {
      this.loading_status = "loading";
      try {
        const response = await this.$u.api.searchOrder({
          ...this.search_form,
          orderType: 23,
          page: this.page,
          pageSize: this.pageSize,
        });
        const data = response.data;
        const cData = data || [];
        if (this.page === 1) {
          this.order_list = cData;
        } else {
          this.order_list = this.order_list.concat(cData);
        }
        this.pageTotal = response.pageTotal || 0;
      } catch (error) {
        console.error("搜索订单失败:", error);
        this.$u.toast("搜索订单失败");
      }
      this.loading_status = "more";
    },
    //  判断
    getData() {
      const isKey = this.$utils.isSerch(this.search_form);
      if (isKey) {
        this.searchOrder();
      } else {
        this.getAllOrder();
      }
    },
    // 下拉加载
    scrollLoading() {
      // 新增：防止多次触发，且保证 loadingMore 标志正确
      if (this.loadingMore) return;
      if (this.page < Math.ceil(this.pageTotal / this.pageSize)) {
        this.page += 1;
        this.loadingMore = true;
        this.getData().finally(() => {
          this.loadingMore = false;
        });
      } else {
        this.loading_status = "noMore";
      }
    },
    //拨打电话
    phoneCall(phone) {
      uni.makePhoneCall({
        phoneNumber: phone, //仅为示例
      });
    },
    // 跳转新增订单页面
    goAddOrder() {
      if (!this.$accessCheck(this.$Access.addSaleOrder)) {
        this.$u.toast("抱歉，您没有新建权限");
        return;
      }
      this.goPage("/pagesB/order/SaleOrderAdd");
    },
    clearKeyword(key) {
      switch (key) {
        case "keyword":
          this.search_form.keyword = "";
          break;
        case "startTime":
          this.startTime = "";
          this.search_form.start = "";
          break;
        case "endTime":
          this.endTime = "";
          this.search_form.end = "";
          break;
      }

      this.searchList();
    },
    clearSearch(key) {
      this[key] = "";
      switch (key) {
        case "regionName":
          this.search_form.provinceCode = "";
          this.search_form.cityCode = "";
          this.search_form.districtCode = "";
          break;
        case "customerName":
          this.search_form.customerId = "";
          break;
        case "customerTypeName":
          this.search_form.customerType = "";
          break;
        case "staffName":
          this.search_form.salesManId = "";
          break;
      }
    },
    // 重置筛选
    resetSearch() {
      this.regionName = "";
      this.search_form.provinceCode = "";
      this.search_form.cityCode = "";
      this.search_form.districtCode = "";
      this.search_form.payType = "";
      this.customerName = "";
      this.search_form.customerId = "";
      this.customerTypeName = "";
      this.search_form.customerType = "";
      this.search_form.source = "";
      this.staffName = "";
      this.search_form.salesManId = "";
    },
    // 客户类型
    async getAllCustomerSource() {
      try {
        const response = await this.$u.api.getAllCustomerSource({
          page: 1,
          pageSize: 99,
        });
        const data = response.data;
        this.customerType = (data || []).map((item) => {
          return {
            ...item,
            label: item.name,
            value: item.id,
          };
        });
        this.customerType.unshift({
          value: "",
          label: "全部",
        });
      } catch (error) {
        console.error("获取客户来源失败:", error);
      }
    },
  },
};
</script>

<style lang="scss">
.container-view {
  /* #ifdef H5*/
  height: calc(100vh - 230upx);
  /* #endif */
  /* #ifdef MP||APP-PLUS */
  height: calc(100vh - 138upx);
  /* #endif */
  // transform: translateY(138upx);
  padding-top: 10px;
  background: #f8f8f8;
  border-radius: 24upx 24upx 0 0;
  box-shadow: 0 -2upx 12upx rgba(0, 0, 0, 0.04);
  overflow: hidden;
}

.top-fixed {
  background: #fff;
  box-shadow: 0 2upx 12upx rgba(0, 0, 0, 0.04);
  border-radius: 0 0 24upx 24upx;
  padding-bottom: 8upx;
}

.top-search {
  display: flex;
  align-items: center;
  padding: 24upx 24upx 0 24upx;
  background: #fff;
  border-radius: 0 0 16upx 16upx;

  .u-icon {
    margin-right: 12upx;
  }
  .top-input {
    flex: 1;
    font-size: 28upx;
    color: #222;
    background: #f8f8f8;
    border-radius: 8upx;
    padding: 12upx 20upx;
    border: 1upx solid #e0e0e0;
    margin: 0 12upx;
    transition: border-color 0.2s;
    &:focus {
      border-color: #fb5904;
      background: #fff;
    }
  }
  .icon-close {
    margin-left: 8upx;
    color: #bbb;
    font-size: 28upx;
  }
}

.search-sel {
  display: flex;
  align-items: center;
  padding: 16upx 24upx 8upx 24upx;
  background: #fff;
  justify-content: space-around;

  .search-sel-li {
    display: flex;
    align-items: center;
    margin-right: 24upx;
    padding: 8upx 18upx;
    // background: #f8f8f8;
    border-radius: 8upx;
    font-size: 26upx;
    color: #666;
    min-width: 120upx;
    cursor: pointer;
    position: relative;

    .sel-label {
      color: #333;
      font-size: 26upx;
      margin-right: 6upx;
    }
    .sel-name {
      color: #fb5904;
      font-weight: 500;
    }
    .ibonshaixuan {
      color: #fb5904;
      font-size: 28upx;
      margin-left: 4upx;
    }
    .ic-down {
      margin-left: 4upx;
      color: #fb5904;
      font-size: 20upx;
    }
    .ibonic_searchclosed {
      font-size: 24upx;
      color: #fb5904;
      margin-left: 4upx;
    }
  }
}

.list-ul {
  padding: 0 0 24upx 0;
}

.list-item {
  background: #fff;
  border-radius: 16upx;
  margin: 18upx 16upx 0 16upx;
  padding: 24upx 24upx 18upx 24upx;
  box-shadow: 0 2upx 12upx rgba(0, 0, 0, 0.06);
  transition: box-shadow 0.2s, transform 0.2s;
  position: relative;
  cursor: pointer;
  border: 1upx solid #f3f3f3;

  &:active {
    box-shadow: 0 4upx 24upx rgba(251, 89, 4, 0.1);
    transform: scale(0.98);
  }

  .sel-view {
    margin-right: 18upx;
    color: #bbb;
    font-size: 30upx;
    .ibonxuanze_xuanzhong {
      color: #fb5904;
    }
  }

  .list-label {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 30upx;
    font-weight: 600;
    color: #222;
    margin-bottom: 6upx;
    .status-text {
      font-size: 24upx;
      font-weight: 400;
    }
  }

  .list-cont {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 26upx;
    color: #666;
    margin-bottom: 4upx;
    .ibonfont {
      font-size: 26upx;
      margin-right: 8upx;
      color: #fb5904;
    }
    .mobile {
      color: #fb5904;
      font-weight: 500;
      cursor: pointer;
    }
    .error-color {
      color: #fb5904;
      font-weight: 600;
      font-size: 28upx;
    }
    .success-color {
      color: #13ce66;
      font-weight: 600;
      font-size: 28upx;
    }
  }

  .uniTag-moni {
    display: inline-block;
    padding: 6upx 18upx;
    background: #fff7f0;
    color: #fb5904;
    border-radius: 20upx;
    font-size: 24upx;
    border: 1upx solid #fb5904;
    margin-top: 6upx;
    cursor: pointer;
    transition: background 0.2s;
    &:active {
      background: #ffe5d0;
    }
  }

  .more-right {
    position: absolute;
    right: 18upx;
    top: 50%;
    transform: translateY(-50%);
    .ibonfont {
      color: #fb5904;
      font-size: 28upx;
      vertical-align: middle;
    }
  }
}

.uni-load-more {
  margin: 24upx 0;
}

.drawer-view {
  .search-bo-btn {
    box-shadow: 0px -4upx 20upx 0upx rgba(251, 89, 4, 0.15);
    position: absolute;
    bottom: 0;
    left: 0;
    display: flex;
    padding: 20upx;
    width: calc(100% - 40upx);
    background: #fff;

    .sb-btn-li:first-child {
      margin-right: 20upx;
    }

    .sb-btn-li {
      flex: 1;
      height: 80upx;
      line-height: 80upx;
      text-align: center;
      color: #666;
      background: #f8f8f8;
      border: 1px solid #e0e0e0;
      border-radius: 8upx;
      font-size: 28upx;
      transition: all 0.3s;

      &:active {
        transform: scale(0.95);
      }
    }

    .sb-btn-li:last-child {
      background: linear-gradient(135deg, #fb5904 0%, #ff7b3d 100%);
      color: #fff;
      border-color: #fb5904;
      box-shadow: 0 4upx 12upx rgba(251, 89, 4, 0.3);
      font-weight: 500;
    }
  }
}

.search-ul {
  padding: 30upx 20upx;
  background: #fff;

  .search-item {
    border-bottom: 1px solid #f0f0f0;
    padding: 20upx 0;

    .search-label {
      line-height: 60upx;
      color: #333;
      font-weight: 500;
    }

    .search-value {
      .search-input {
        font-size: 26upx;
        height: 60upx;
        line-height: 60upx;
        border-radius: 8upx;
        padding: 0 20upx;
        background: #f8f8f8;
        border: 1upx solid #e0e0e0;

        &:focus {
          border-color: #fb5904;
          background: #fff;
        }

        .ibonjinru {
          color: #fb5904;
        }

        .ibonic_searchclosed {
          font-size: 28upx;
          color: #fb5904;
          margin-right: 30upx;
        }
      }
    }
  }
}

/* 新增按钮样式 */
.add-btn-fixed {
  position: fixed;
  bottom: 150rpx;
  right: 30rpx;
  width: 120rpx;
  height: 120rpx;
  background: linear-gradient(135deg, #fb5904, #ff7b3d);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 24rpx rgba(251, 89, 4, 0.4);
  z-index: 999;
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.95);
    box-shadow: 0 4rpx 12rpx rgba(251, 89, 4, 0.6);
  }

  .add-btn-icon {
    color: #fff;
    font-size: 48rpx;
    font-weight: bold;
    line-height: 1;
  }
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 100upx 40upx;
  color: #999;

  .empty-icon {
    font-size: 120upx;
    color: #e0e0e0;
    margin-bottom: 20upx;
  }

  .empty-text {
    font-size: 28upx;
    color: #999;
  }
}
</style>
